<?php
class Product_Service_QualityControlOrder
{
	public static $statusText = array(
		"0" => "草稿",
		"1" => "确认",
		"2" => "完成",
		//"3" => "异常",
		//"4" => "删除",
	);
	
	public  static $problem_type=array(
			"1" => "来货不符",
			"2" => "破损或变形",
			"3" => "少配件",
	);

    public  static $exportType=array(
        "1" => "收货日期",
        "2" => "质检日期",
    );

	public static function getByCondition($condition=array(),$type='*',$order=array('qco_id'), $pageSize=0, $page=1)
	{ 
		if(isset($condition["date_from"]) && $condition['date_from'] != ""){
			$condition['date_from']=date('Y-m-d',strtotime("{$condition['date_from']}"))." 00:00:00"; 
		}
		if(isset($condition["date_to"]) && $condition['date_to'] != ""){
			$condition['date_to']=date('Y-m-d',strtotime("{$condition['date_to']}"))." 23:59:59"; 
		}
		$obj=new Product_Model_QualityControlOrder();
		$rows= $obj->getByCondition( $condition,$type,$order, $pageSize,$page);
		if(is_array($rows)){
			foreach($rows as $key => $val){
				$rows[$key]["statusText"] = self::$statusText[$val['qco_status']];
				$userRow=User_Service_User::getByUserId($val['user_id']);
				$rows[$key]["user_id"] = $userRow['name'];
			}
		}
		return $rows;
	}
	
	public function getAdapter(){
		$model = new Product_Model_QualityControlOrder();
		return $model->getAdapter();
	}
	
	public static function add($row){
		$model = new Product_Model_QualityControlOrder();
		return $model->add($row);
	}
	
	public static function update($row,$id){
		$model = new Product_Model_QualityControlOrder();
		return $model->update($row,$id);
	}
	
	public static function delete($qco_id){
		$model = new Product_Model_QualityControlOrder();
		return $model->delete($qco_id);
	}
	
	public static function deleteByQcoCode($qco_code){
		$model = new Product_Model_QualityControlOrder();
		$itemModel = new Product_Model_QualityControlItem();
		$result1=$itemModel->deleteByQcoCode($qco_code);
		$result2=$model->deleteByQcoCode($qco_code);
		if($result1 && $result2){
			return false;
		}
		return true;
	}
	
	public static function getQcoCode($qco_code){
		$model = new Product_Model_QualityControlOrder();
		$row=$model->getQcoCode($qco_code);
		if(!empty($row)){
			return $row->toArray();
		}
		return $row;
	}
	
	/*
	*根据参考号及产品ID获取通过QC的数量
	*param qco_ref_code product_id
	*retrun int 
	*/
	public static function getByQcoRefCodeAndProductId($qco_ref_code=null,$product_id=0){
		if($qco_ref_code=='' || $product_id==0 ){
			return 0;
		}
		$qc_count=0;//通过数量
		$QcAll= self::getByCondition(array('qco_ref_code'=>$qco_ref_code,'qco_status'=>2),'*','',0,0);
		if(!empty($QcAll)){
			foreach($QcAll as $key => $val){
				$itemAll=Product_Service_QualityControlItem::getByCondition(array('qco_code'=>$val['qco_code'],'product_id'=>$product_id,'qci_status'=>3),'*','');
				foreach($itemAll as $k => $v){
					$qc_count+=$v['qci_quantity_pass'];
				}
			}
		}
		return $qc_count;
	}
	
	/*
	*根据参考号获取信息
	*/
	public static function getByQcoRefCode($qco_ref_code){
		$model = new Product_Model_QualityControlOrder();
		$row=$model->getByQcoRefCode($qco_ref_code);
		if(!empty($row)){
			return $row->toArray();
		}
		return $row;
	}
	
	public static function getArrayByQcoRefCode($qco_ref_code){
		$model = new Product_Model_QualityControlOrder();
		$res = $model->getArrayByQcoRefCode($qco_ref_code);
		return $res->toArray();
	}
	/*
	 * 获取当天最后一个 qco_code
	 */
	public static function getCurdateLastCode()
	{ 
		$obj=new Product_Model_QualityControlOrder();
		$rows=$obj->getCurdateLastCode();
		$QCNO = 'Q'.date('ymd');
		$tmp ='';
		if($rows){
			$tmp= (int) substr($rows,-3,3);
			$tmp= str_pad(($tmp+1),3,'0',STR_PAD_LEFT);
		}else{
			$tmp ='001';
		}
		$QCNO.=$tmp;
		return $QCNO;
	}
	
	/*
	*根据ASN、产品ID、实收数量，创建QC信息
	*param string receiving_code,int product_id,int received_qty,strint qco_code
	*return true 成功 false 失败
	*/
	public static function getAddQcOrder($receiving_code=null,$product_id=0,$received_qty=0,$qco_code=null){
		if($receiving_code==null || $product_id<1 || $received_qty<1 || $qco_code==''){
// 			var_dump($receiving_code);
// 			var_dump($product_id);
// 			var_dump($received_qty);
// 			var_dump($qco_code);
// 			exit;
			return false;
		}
		$receiving =Product_Service_Receiving::getByReceivingCode($receiving_code);
		if(empty($receiving)){
			return false;
		}
		$customer_id=$receiving['customer_id'];
		$session = new Zend_Session_Namespace('userAuth');
		$user_id=$session->userID;					//操作人
		$model = new Product_Model_QualityControlOrder();
		$ItemModel = new Product_Model_QualityControlItem();

		$OrderRef=self::getQcoCode($qco_code);
    	$addRow=array(
				'qco_code'=>$qco_code,
				'customer_id'=>$customer_id,
				'qco_quantity'=>$received_qty,
				'qco_ref_code'=>$receiving_code,
				'user_id'=>$user_id,
				'qco_status'=>1,//确认状态
				);
		 if(!$model->add($addRow)){
		 	
			return false;
		 }		
		/*
		//判断是否已存在
		if(empty($OrderRef)){
			$addRow=array(
				'qco_code'=>$qco_code,
				'customer_id'=>$customer_id,
				'qco_quantity'=>$received_qty,
				'qco_ref_code'=>$receiving_code,
				'user_id'=>$user_id,
				//'qco_status'=>0,
			);
			if(!$model->add($addRow)){
				return false;
			}
		}else{
			//更新总质检数量
			$update=array(
				'qco_quantity'=>$OrderRef['qco_quantity']+$received_qty,
			);
			if(!$model->update($update,$OrderRef['qco_id'])){
				return false;
			}
		}
		*/
		//添加Item
		$addItem=array(
			'qco_code'=>$qco_code,
			'product_id'=>$product_id,
			'qci_quantity'=>$received_qty,
		);
		if(!$ItemModel->add($addItem)){
			return false;
		}
		return true;
	}
	public static function getOperationResult($qco_code){
		$res = self::getQcoCode($qco_code);
		
		//质检员ID
		$session = new Zend_Session_Namespace('userAuth');
		$user_id = $session->userID;
		//收货时间 与 收货员ID
		$receiving = Product_Service_Receiving::getByReceivingCode($res['qco_ref_code']);
		
		$res['order_type']=$receiving['order_type'];

		$qcUserRes = User_Service_User::getByUserId($user_id);
		$res['qc_uname'] = $qcUserRes['name'];
		
		//获取产品信息 1.QC_CODE -> PRODUCT_ID
		$pidsRes = Product_Service_QualityControlItem::getQcoCodeAll($qco_code);
		//PID -> PRODUCT_SKU 
		//PID + PO_ID -> PO_VALUE POC_ID
		//POC_ID -> POC_VLAUE
		$povModel = new Product_Model_ProductOptionValue();
		$pocModel = Product_Model_ProductOptionChoose::getInstance();
		$qciModel = Product_Model_QualityControlItem::getInstance();
		$objConfig = new Default_Model_Config();
		$congifRes = $objConfig->getByValue('QUANTITY_CONTROL_ID');
		foreach($pidsRes as $key=>$val){
			$recevingItemRes = Product_Service_ReceivingItem::getByReceivingAsnPid(array('product_id'=>$val['product_id'],'receiving_code'=>$res['qco_ref_code']));
			$res['ri_sort'] = $recevingItemRes['ri_sort']==1 ? '优先' : '正常';
			$res['is_qc']=$recevingItemRes['is_qc'];

            $res['recevice_date'] = $recevingItemRes['receivetime'];
            //收货员
            $res['reccvice_uname'] = '';
            if($recevingItemRes['modified_by']!=''){
                $receviceUserRes = User_Service_User::getByUserId($recevingItemRes['modified_by']);
                $res['reccvice_uname'] = $receviceUserRes['name'];
            }

			$productRes = Product_Service_Product::getByProductId($val['product_id']);
			$povRes = $povModel->getByProductId($val['product_id'],$congifRes['config_value']);//返回多条
			$temp = array();
			//如果是质检
			if($res['is_qc']){
				
				foreach($povRes as $k=>$v){
					$pocRes = $pocModel->getByPocid($v['poc_id']);
					$qciRes = $qciModel->getByQcoCodeAndProductId($qco_code,$val['product_id']);
					$proAttId = Product_Service_Receiving::getPicturesPath($val['product_id']);
					$temp[] = array(
							'product_sku'=>$productRes['product_sku'],
							'customer_id'=>$productRes['customer_id'],
							'product_weight'=>$productRes['product_weight'],
							'poc_value_cn'=>$pocRes['poc_value_cn'],
							'po_value'=>$v['po_value'],
							'pov_id'=>$v['pov_id'],
							'poc_id'=>$v['poc_id'],
							'qci_quantity'=>$qciRes['qci_quantity'],
							'proAttId'=>$proAttId);
				}
				
			}else{
				$qciRes = $qciModel->getByQcoCodeAndProductId($qco_code,$val['product_id']);
				$proAttId = Product_Service_Receiving::getPicturesPath($val['product_id']);
				$temp[] = array(
						'product_sku'=>$productRes['product_sku'],
						'customer_id'=>$productRes['customer_id'],
						'product_weight'=>$productRes['product_weight'],
						'poc_value_cn'=>'',
						'po_value'=>0,
						'pov_id'=>0,
						'poc_id'=>0,
						'qci_quantity'=>$qciRes['qci_quantity'],
						'proAttId'=>$proAttId,
						'order_type'=>$res['order_type']
						);
				
				
			}
			
			$res['product_info'][$val['product_id']] = $temp;
		}		
		return $res;
	}
	public static function getDetailResult($qco_code){
		//更新状态
		$qcoModel = new Product_Model_QualityControlOrder();
		$res = self::getQcoCode($qco_code);
		
		if($res['qco_status']==0){
			$qcoModel->updateByQcoCode(array('qco_status'=>'1'),$qco_code); 
		}
		
		//质检员ID
		$session = new Zend_Session_Namespace('userAuth');
		$user_id = $session->userID;
		//收货时间 与 收货员ID
		$receiving = Product_Service_Receiving::getByReceivingCode($res['qco_ref_code']);
		
		$res['order_type']=$receiving['order_type'];		
		$res['receiving']=$receiving;

		$qcUserRes = User_Service_User::getByUserId($user_id);
		//$res['qc_uname'] = $qcUserRes['name'];
		//质检时间
		$qcoRes = Product_Model_QualityControlOrder::getInstance()->getQcoCode($qco_code);
		$res['qco_last_update'] = ($qcoRes['qco_last_update'] == '0000-00-00 00:00:00' ? '' : $qcoRes['qco_last_update']);
		
		//获取产品信息 1.QC_CODE -> PRODUCT_ID
		$pidsRes = Product_Service_QualityControlItem::getQcoCodeAll($qco_code);
		//PID -> PRODUCT_SKU 
		//PID + PO_ID -> PO_VALUE POC_ID
		//POC_ID -> POC_VLAUE
		$povModel = new Product_Model_ProductOptionValue();
		$pocModel = Product_Model_ProductOptionChoose::getInstance();
		$qciModel = Product_Model_QualityControlItem::getInstance();
		$objConfig = new Default_Model_Config();
		$congifRes = $objConfig->getByValue('QUANTITY_CONTROL_ID');

		foreach($pidsRes as $key=>$val){
            
			$getQcNameRow=User_Service_User::getByUserId($val['user_id']);
			$res['qc_uname']=$getQcNameRow['name'];
			
			$qciRows=Product_Service_QualityControlItem::getQcoCodeAll($qco_code);
            $recevingItemRes = Product_Service_ReceivingItem::getByReceivingAsnPid(array('product_id'=>$val['product_id'],'receiving_code'=>$res['qco_ref_code']));
            $res['is_qc']=$recevingItemRes['is_qc'];
			$res['ri_sort'] = $recevingItemRes['ri_sort']==1 ? '优先' : '正常';

            $res['recevice_date'] = $recevingItemRes['receivetime'];
            //收货员
            $res['reccvice_uname'] = '';
            if($recevingItemRes['modified_by']!=''){
                $receviceUserRes = User_Service_User::getByUserId($recevingItemRes['modified_by']);
                $res['reccvice_uname'] = $receviceUserRes['name'];
            }

			$productRes = Product_Service_Product::getByProductId($val['product_id']);
			$povRes = $povModel->getByProductId($val['product_id'],$congifRes['config_value']);//返回多条
			$qciRes = $qciModel->getByQcoCodeAndProductId($qco_code,$val['product_id']);
			$qcrModel = Product_Model_QualityControlResult::getInstance();
			$temp = array();
            $defaultWscode='';//推荐货架号 有可能上架后会有多个。默认第一个
            $putawayContion = array(
                'product_id' => $val['product_id'] ,
                'receiving_code' => $res['qco_ref_code'],
            );
            $putawayRows = Product_Service_Putaway::getByCondition($putawayContion, "*");
            if(!empty($putawayRows)){
                 $defaultWscode = $putawayRows[0]['ws_code'];
            }
			//如果是质检
			if($res['is_qc']){
				$problem_type=Product_Service_QualityControlOrder::$problem_type;
				
				foreach($povRes as $k=>$v){
					$pocRes = $pocModel->getByPocid($v['poc_id']);
					$qcrRes = $qcrModel->getByPovIdAndQciId($v['pov_id'],$qciRes['qci_id']);
					$proAttId = Product_Service_Receiving::getPicturesPath($val['product_id']);

					$problemType='';
					if(isset($problem_type[isset($qcrRes['qcr_problem_type'])?$qcrRes['qcr_problem_type']:''])){
						$problemType=$problem_type[isset($qcrRes['qcr_problem_type'])?$qcrRes['qcr_problem_type']:''];
					}
					$temp[] = array(
							'product_sku'=>$productRes['product_sku'],
							'customer_id'=>$productRes['customer_id'],
							'product_weight'=>$recevingItemRes['weight'],//返回QC完成后的重量
							'poc_value_cn'=>$pocRes['poc_value_cn'],
							'po_value'=>$v['po_value'],
							'qcr_problem_type'=>$problemType,
							'poc_id'=>$v['poc_id'],
							'qco_real_quantity'=>$res['qco_real_quantity'],
							'qco_note'=>$res['qco_note'],
							'qcr_quantity_problem'=>isset($qcrRes['qcr_quantity_problem'])?($qcrRes['qcr_quantity_problem']==0 ? '' : $qcrRes['qcr_quantity_problem']):'',
							'ws_code'=>$qciRes['ws_code'],
							'qci_quantity'=>$qciRes['qci_quantity'],
							'qci_quantity_problem'=>($qciRes['qci_quantity_problem'] == 0 ? '' : $qciRes['qci_quantity_problem']),
							'qcr_description'=>isset($qcrRes['qcr_description'])?$qcrRes['qcr_description']:'',
							'proAttId'=>$proAttId,
							'default_ws_code'=>$defaultWscode);
				}
				
			}else{
				$proAttId = Product_Service_Receiving::getPicturesPath($val['product_id']);
				$temp[] = array(
						'product_sku'=>$productRes['product_sku'],
						'customer_id'=>$productRes['customer_id'],
						'product_weight'=>$recevingItemRes['weight'],//返回QC完成后的重量
						'poc_value_cn'=>0,
						'po_value'=>0,
						'poc_id'=>0,
						'qco_real_quantity'=>$res['qco_real_quantity'],
						'qco_note'=>$res['qco_note'],
						'qcr_quantity_problem'=>0,
						'ws_code'=>$qciRes['ws_code'],
						'qci_quantity'=>$qciRes['qci_quantity'],
						'qci_quantity_problem'=>($qciRes['qci_quantity_problem'] == 0 ? '' : $qciRes['qci_quantity_problem']),
						'qcr_description'=>0,
						'proAttId'=>$proAttId,
						'default_ws_code'=>$defaultWscode);
	
			}
			
			$res['product_info'][$val['product_id']] = $temp;
		}
		//print_r($res);
		return $res;
	}
	
	public static function qcConfirmService($arr){
		
		//print_r($arr);exit;//更新quality_control_order qco_code
		$date=date("Y-m-d:H:i:s");
		$session = new Zend_Session_Namespace('userAuth');
		$user_id=$session->userID;
		
		$qcoModel = new Product_Model_QualityControlOrder();  
		$qcoModel->getAdapter()->beginTransaction();
		try{
            $qcRow=$qcoModel->getQcoCode($arr['qco_code']);
            if(empty($qcRow)){
                return array(
                    "ask" =>0,
                    "msg" => "数据异常.",
                );
            }elseif($qcRow['qco_status']!='1'){
                return array(
                    "ask" =>0,
                    "msg" => "确认状态下才可以进行QC,请核查当前状态.",
                );
            }
			$qco_quantity_problem = 0;
			foreach($arr['qci_quantity_problem'] as $value){
				$qco_quantity_problem+=$value;
			}
			if($arr['qco_real_quantity']>0){
				$qco_quantity_pass = $arr['qco_real_quantity']-$qco_quantity_problem;
			}else{
				$qco_quantity_pass=0;
			}


            //更新ASN item 产品重量
            $productWeight=$arr['product_weight'];
            $productId=$arr['product_id'][0]; //目前一个QC 只有一个产品
            $receivingCode=$arr['qco_ref_code'];
            $date=date('Y-m-d H:i:s');
            if(!is_numeric($productWeight)){
                return array(
                    "ask" =>0,
                    "msg" => "重量必须是数字",
                );
            }
            $where = array(
                'product_id' => $productId,
                'receiving_code' => $receivingCode,
            );
            $updateRow = array(
                'weight' => $productWeight ,
                'modified'=> date('Y-m-d H:i:s'),
            );
            if (!Product_Service_ReceivingItem::updateAsnPid($updateRow, $where)) {
                $qcoModel->getAdapter()->rollBack();
                return array(
                    "ask" =>0,
                    "msg" => "更新ASN-Item重量失败."
                );
            }
			
			$qcoUpdateRow = array('qco_quantity_pass'=>$arr['is_qc']==1?$qco_quantity_pass:$arr['qco_real_quantity'],
								  'qco_quantity_problem'=>$arr['is_qc']==1?$qco_quantity_problem:0,
					              'qco_real_quantity'=>$arr['qco_real_quantity'],
					              'qco_note'=>$arr['qco_note_order'],
								  'qco_status'=>'2',
								  'qco_last_update'=>$date);
			$qcoModel->updateByQcoCode($qcoUpdateRow ,$arr['qco_code']);
			//更新quality_control_item  qco_code product_id 更新不良库存
			//需要在更新的同时 向quality_control_result增添记录
			//QC通过 创建上架单 
			$session = new Zend_Session_Namespace('userAuth');
			$user_id = $session->userID;
			$qciModel = new Product_Model_QualityControlItem();
			$putaway_lot_number = 1;
			
			foreach($arr['qci_quantity_problem'] as $key=>$val){
				$qciRes = Product_Service_QualityControlItem::getByQcoCodeAndProductId($arr['qco_code'],$key);
				if($arr['qco_real_quantity']>0){
					$qci_quantity_pass=$arr['qco_real_quantity']-$val;
				}else{
					$qci_quantity_pass=0;
				}
				
				
				if($arr['is_qc']){
					//更改上架状态判断
					if($arr['qco_real_quantity']==0 || $qci_quantity_pass==0){
						$putawayStatus=1;
					}else{
						$putawayStatus=0;
					}
					//上架数量
					$putawayQuantity=$qci_quantity_pass;
					$qciQuantityProblem=$val;
				}else{
					if($arr['qco_real_quantity']==0){
						$putawayStatus=1;
					}else{
						$putawayStatus=0;
					}
					$putawayQuantity=$arr['qco_real_quantity'];
					$qciQuantityProblem=0;
				}
				
				
				
				$qciUpdateRow = array('qci_status'=>3,
									  'qci_quantity_pass'=>$putawayQuantity,
									  'qci_quantity_problem'=>$qciQuantityProblem,
									  'user_id'=>$user_id,
									  'ws_code'=>$arr['ws_code'][$key],
									  'qci_last_update'=>$date);
				$qciModel->updateByQcoCodeAndProductId($qciUpdateRow,$arr['qco_code'],$key);
				
				//[281] => Array([15] => 1 [14] => 2)
				//[280] => Array([15] => 3 [18] => 4)
				foreach($arr['qco_quantity_problem'][$key] as $k=>$v){
					
					if($arr['qco_real_quantity']>0){
						$qcr_quantity_pass =$arr['qco_real_quantity']-$v;
					}else{
						$qcr_quantity_pass=0;
					}
					
					if($arr['is_qc']){
						$qcrQuantityPass=$qci_quantity_pass;
						$qcrProblemType=$arr['qcr_problem_type'][$key][$k];
					}else{
						$qcrQuantityPass=$arr['qco_real_quantity'];
						$qcrProblemType=0;
					}
					
					$qcrInsertRow = array('qci_id'=>$qciRes['qci_id'],
										  'pov_id'=>$k,
										  'qcr_quantity_problem'=>$v,
										  'qcr_quantity_pass'=>$qcrQuantityPass,
							              'qcr_problem_type'=>$qcrProblemType,
										  'qcr_description'=>$arr['qco_note'][$key][$k],
										  'qcr_create_time'=>$date);
					Product_Service_QualityControlResult::add($qcrInsertRow);
				}
				
				$receiving_code = $arr['qco_ref_code'];
				$receivingRes = Product_Service_Receiving::getByReceivingCode($receiving_code);
				$warehouse_id = $receivingRes['warehouse_id'];
				
				$putawayRowArr=array(
						'putaway_status'=>'-1',
						'receiving_code'=>$receiving_code,
						'warehouse_id'=>$warehouse_id,
						'product_id'=>$key
				);
				
				$putawayRow=Product_Service_Putaway::getByCondition($putawayRowArr,'*',0,0);
				
				
				
				
				
				//更新上架数量
				$putawayUpdateRow = array(
						'putaway_status'=>$putawayStatus,
						'putaway_quantity'=>$putawayQuantity);
				$updatePutawayResult=Product_Service_Putaway::updateQtyByRcodeAndPid($putawayUpdateRow,$receiving_code,$key);
				
				if(!$updatePutawayResult){
					$qcoModel->getAdapter()->rollBack();
					$data=array(
								'ask'=>0,
								'msg'=>'更新上架信息失败'
								);
						return $data;
				}
				

				if($putawayRow){
					$pl_note='';
					if($arr['qco_real_quantity']=='0'){
						$pl_note='QC确认后,实收数量为0，上架单状态被更新为完成:1';
					}else{
						$pl_note="产品ID:".$key." QC确认后,上架数量改为:".$arr['qco_real_quantity'];
					}
					$putawayLogRow=array(
							'putaway_code'=>$putawayRow[0]['putaway_code'],
							'pl_note'=>$pl_note
					);
					
					$resultCreatePutawayLog=Product_Service_Putaway::createPutawayLog($putawayLogRow);
					if(!$resultCreatePutawayLog){
						$qcoModel->getAdapter()->rollBack();
						$data=array(
								'ask'=>0,
								'msg'=>'创建上架日志失败'
								);
						return $data;
					}
					
					//更改ASN实收数量
					$rowRi=array(
							'received_qty'=>$arr['qco_real_quantity'],
							'status'=>3,//0:未收货;1:收货中;2:已收货;3：已质检;
							'modified'=>$date
							);
					$RiCond=array(
							'receiving_code'=>$putawayRow[0]['receiving_code'],
							'product_id'=>$key
							);
					$updateRiResult=Product_Service_ReceivingItem::updateAsnPid($rowRi, $RiCond);
					if(!$updateRiResult){
						$qcoModel->getAdapter()->rollBack();
						$data=array(
								'ask'=>0,
								'msg'=>'更新收货清单的[收货数量]失败'
						);
						return $data;
					}
					
					
				}else{
					$qcoModel->getAdapter()->rollBack();
					$data=array(
								'ask'=>0,
								'msg'=>'找不到上架单号'.$putawayRow[0]['putaway_code']
								);
					return $data;
				}
				
				//如果是质检
				if($arr['is_qc']){
					//更新不良品库存
					$psRes = Product_Service_ProductStocket::getByProductId($key,$warehouse_id);
					$ps_quantity_problem = $psRes['ps_quantity_problem']+$val;
					if($psRes){
						$updatePskResult=Product_Service_ProductStocket::update(array('ps_quantity_problem'=>$ps_quantity_problem),$key,$warehouse_id);
						if(!$updatePskResult){
							$qcoModel->getAdapter()->rollBack();
							$data=array(
									'ask'=>0,
									'msg'=>'更新问题库存数量失败'
							);
							return $data;
						}else{
							//创建总库存日志
							$rowAddPslog=array(
									'product_id'=>$key,
									'user_id'=>$user_id,
									'psl_type'=>1,
									'psl_note'=>'更新总库存[不良品数量]由:'.$psRes['ps_quantity_problem'].'变为:'.$ps_quantity_problem,
									'psl_add_time'=>$date
							);
							$rowAddPslogResult=Product_Service_ProductStocketLog::create($rowAddPslog);
							if(!$rowAddPslogResult){
								$qcoModel->getAdapter()->rollBack();
								$data=array(
										'ask'=>0,
										'msg'=>'更新总库存[不良品数量]记录日志失败'
								);
								return $data;
							}
					   }
					}else{
						//创建新的总库存记录
						$rowAddPs=array(
								'product_id'=>$key,
								'warehouse_id'=>$warehouse_id,
								'ps_quantity_problem'=>$ps_quantity_problem,
								'ps_create_date'=>$date
								);
						$rowAddPsResult=Product_Service_ProductStocket::create($rowAddPs);
						if(!$rowAddPsResult){
							$qcoModel->getAdapter()->rollBack();
							$data=array(
									'ask'=>0,
									'msg'=>'创建总库存记录失败'
							);
							return $data;
						}else{
							//创建总库存日志
							$rowAddPslog=array(
									'product_id'=>$key,
									'user_id'=>$user_id,
									'psl_type'=>1,
									'psl_note'=>'第一次收货，发现[不良品]并录入问题库存数量变为:'.$ps_quantity_problem,
									'psl_add_time'=>$date
									);
							$rowAddPslogResult=Product_Service_ProductStocketLog::create($rowAddPslog);
							if(!$rowAddPslogResult){
								$qcoModel->getAdapter()->rollBack();
								$data=array(
										'ask'=>0,
										'msg'=>'总库存记录日志失败'
								);
								return $data;
							}
						}
					}
					
				}else{
					
					//如果是特采
					if($arr['order_type']==4){
						$rowPs=Product_Service_ProductStocket::getByProductId($key,$warehouse_id);
						if(!$rowPs){
							$qcoModel->getAdapter()->rollBack();
							$data=array(
									'ask'=>0,
									'msg'=>'总库存不存在该产品'
							);
							return $data;
						}else{
							//查看不良品数量
							if($rowPs['ps_quantity_problem']<$arr['qco_real_quantity']){
								$qcoModel->getAdapter()->rollBack();
								$data=array(
										'ask'=>0,
										'msg'=>'总库存[不良品数量]不能小于实收总数量'
								);
								return $data;
							}
							
							
						}
						
						$changetoQuantity=$rowPs['ps_quantity_problem']-$arr['qco_real_quantity'];
						//更新总库存记录的问题数
						$rowUpdatePs=array(
								'product_id'=>$key,
								'warehouse_id'=>$warehouse_id,
								'ps_quantity_problem'=>$changetoQuantity,
								'ps_create_date'=>$date
						);
						$psModel=new Product_Service_ProductStocket();
						$rowUpdatePsResult=$psModel->update($rowUpdatePs, $key,$warehouse_id);
						if(!$rowUpdatePsResult){
							$qcoModel->getAdapter()->rollBack();
							$data=array(
									'ask'=>0,
									'msg'=>'更新总库存[不良品数量]记录失败'
							);
							return $data;
						}else{
							
							//创建总库存日志
							$rowAddPslog=array(
									'product_id'=>$key,
									'user_id'=>$user_id,
									'psl_type'=>1,
									'psl_note'=>'更新总库存[不良品数量]由:'.$rowPs['ps_quantity_problem'].'变为:'.$changetoQuantity,
									'psl_add_time'=>$date
							);
							$rowAddPslogResult=Product_Service_ProductStocketLog::create($rowAddPslog);
							if(!$rowAddPslogResult){
								$qcoModel->getAdapter()->rollBack();
								$data=array(
										'ask'=>0,
										'msg'=>'更新总库存[不良品数量]记录日志失败'
								);
								return $data;
							}
						}
						
					}
					
					
				}
				
				$putaway_lot_number++;
			}
			
			
			$qcoModel->getAdapter()->commit();
			$data=array(
						'ask'=>1,
						'msg'=>'ok'
					);
			return $data;
		}catch (Exception $e) {
			echo $e->getTraceAsString(); echo $e->getMessage();
			$qcoModel->getAdapter()->rollBack();
			$logger =  Zend_Registry::get('log');
			$logger->info(date('Y-m-d H:i:s').': '.$e->getMessage()." \n");
            $data=array(
                'ask'=>0,
                'msg'=>'内部错误,'.$e->getMessage()
            );
            return $data;
		}
	}

    /*
     * 导出QC报表数据
     */
    public static function  exportData($condition = array())
    {
        $keyValues = array(
            'No' => '序号',
            'receivetime' => '收货日期',
            'qctime' => '质检日期',
            'contact' => 'PO发出人',
            //'contact_mobile'=>'联系方式',
            'ref_id' => 'PO单',
            'receiving_code' => 'ASNCode',
            'qco_code' => '质检单号',
            'product_sku' => '产品SKU',
           // 'customer_id' => '客户ID',
            'qco_quantity' => '送货数量',
            'qco_real_quantity' => '到货数量',
            'qco_quantity_pass' => '合格数量',
            'qco_quantity_problem' => '不合格数量',
            'receive_user_name' => '收货员',
            'qc_user_name' => '质检员',
            'putaway_user_name' => '上架员',
            'qco_note' => '质检备注',
        );

        //收货日期
        if ($condition['exportType'] == '1') {
            $qcCondition = array(
                'date_from' => $condition['startData'] . ' 00:00:00',
                'date_to' => $condition['endData'] . ' 23:59:59',
            );
            $orderby = array('qco_create_time');
        } else {
            //质检日期
            $qcCondition = array(
                'exportType' => $condition['exportType'],
                'startData' => $condition['startData'] . ' 00:00:00',
                'endData' => $condition['endData'] . ' 23:59:59',
            );
            $orderby = array('qco_last_update');
        }
        $qcRows = self::getByCondition($qcCondition, '*', $orderby, 0, 0);
        foreach ($qcRows as $key => $val) {
            $qcRows[$key]['No'] = $key + 1;
            $qcRows[$key]['receiving_code'] = $val['qco_ref_code'];
            //收货员暂时使用QC创建人
            $qcRows[$key]['receive_user_name'] =$val['user_id'];
            $asnRow = Product_Service_Receiving::getByReceivingCode($val['qco_ref_code']);
            $qcRows[$key]['ref_id'] = isset($asnRow['ref_id']) ? $asnRow['ref_id'] : '';
            $qcRows[$key]['contact'] = isset($asnRow['contact']) ? $asnRow['contact'] : '';
            $qcRows[$key]['contact_mobile'] = isset($asnRow['contact_mobile']) ? $asnRow['contact_mobile'] : '';
            $qcRows[$key]['receivetime'] = $val['qco_create_time'];
            //qc时间,暂时用order最后修改时间
            $qcRows[$key]['qctime'] = strtotime($val['qco_last_update'])?$val['qco_last_update']:'';

            $qcItemRows = Product_Service_QualityControlItem::getQcoCodeAll($val['qco_code']);
            //配置item数据
            if (!empty($qcItemRows)) {
                $qcRows[$key]['product_id'] = $qcItemRows[0]['product_id'];
                $productRow = Product_Service_Product::getByProductId($qcItemRows[0]['product_id']);
                $qcRows[$key]['product_sku'] = isset($productRow['product_sku']) ? $productRow['product_sku'] : '';
                $qcRows[$key]['qci_quantity'] = $qcItemRows[0]['qci_quantity'];
                $qcRows[$key]['qci_quantity_pass'] = $qcItemRows[0]['qci_quantity_pass'];
                $qcRows[$key]['qci_quantity_problem'] = $qcItemRows[0]['qci_quantity_problem'];
                $qcRows[$key]['qci_putaway_qty'] = $qcItemRows[0]['qci_putaway_qty'];
                $userRow = User_Service_User::getByUserId($qcItemRows[0]['user_id']);
                $qcRows[$key]['qc_user_name'] = isset($userRow['name']) ? $userRow['name'] : '';
                $qcRows[$key]['qci_note'] = $qcItemRows[0]['qci_note'];
                //上架员
                $qcRows[$key]['putaway_user_name'] = '';
                if (!empty($asnRow)) {
                    $putawayRows = Product_Service_Putaway::getByCondition(array('product_id' => $qcItemRows[0]['product_id'], 'receiving_code' => $asnRow['receiving_code'], 'putaway_status' => 1), "*");
                    if (!empty($putawayRows)) {
                        $userRow = User_Service_User::getByUserId($putawayRows[0]['putaway_user_id']);
                        $qcRows[$key]['putaway_user_name'] = isset($userRow['name']) ? $userRow['name'] : '';
                    }
                }
            }
        }
        $qcStr = '';
        foreach ($keyValues as $key => $val) {
            $qcStr .= $val . ",";
        }
        $qcStr = trim($qcStr, ',') . "\n";
        if (count($qcRows) > 0) {
            foreach ($qcRows as $qckey => $qcval) {
                foreach ($keyValues as $key => $val) {
                    $qcStr .= (isset($qcval[$key]) ? $qcval[$key] : '') . ",";
                }
                $qcStr = trim($qcStr, ',') . "\n";
            }
        }
        return iconv("utf-8", "gb2312", $qcStr);
    }

}